/**
 * @Title: WorkVisitActivity.java
 * @Package: com.jason.fingerprint.ui
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月9日 下午8:00:43
 * @Version: V1.0
 */
package com.jason.fingerprint.ui;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.*;
import android.fpi.MtRfid;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import com.baidu.location.LocationClient;
import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.R;
import com.jason.fingerprint.adapter.WorkVisitAdapter;
import com.jason.fingerprint.beans.RecordBean;
import com.jason.fingerprint.beans.UserBean;
import com.jason.fingerprint.beans.WorkVisitBean;
import com.jason.fingerprint.beans.ui.FingerPrintBean;
import com.jason.fingerprint.beans.ui.ImageOrAudioBean;
import com.jason.fingerprint.beans.ui.LocationBean;
import com.jason.fingerprint.beans.ui.SoundBean;
import com.jason.fingerprint.common.DataHelper;
import com.jason.fingerprint.common.DialogHelper;
import com.jason.fingerprint.common.SoundRecorder;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.listener.MyLocationListener;
import com.jason.fingerprint.logic.InsertVisitSyncLogic;
import com.jason.fingerprint.logic.MatchFingerprintSyncLogic;
import com.jason.fingerprint.logic.UploadToTempSyncLogic;
import com.jason.fingerprint.widget.LoadingDialog;
import org.kymjs.aframe.database.DbModel;
import org.kymjs.aframe.database.KJDB;
import org.kymjs.aframe.ui.BindView;
import org.kymjs.aframe.ui.KJActivityManager;
import org.kymjs.aframe.ui.activity.BaseActivity;
import org.kymjs.aframe.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @ClassName: WorkVisitActivity
 * @Description: 工作走访
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月9日 下午8:00:43
 */
@SuppressLint("HandlerLeak")
public class WorkVisitActivity extends BaseActivity implements
		OnItemClickListener {

	private static final String TAG = "WorkVisitActivity";
	public static final int CHOOSE_RECORD_REQUEST_OK = 1002;
	public static final int CHOOSE_RECORD_PHOTO_REQUEST_OK = 1003;

	private static final boolean DEBUG = false;

	@BindView(id = R.id.header_back, click = true)
	private Button mBackButton;
	@BindView(id = R.id.header_title)
	private TextView mTitleTextView;
	@BindView(id = R.id.work_visit_listview)
	private ListView mListView;
	@BindView(id = R.id.work_visit_button_sign_in, click = true)
	private Button mSignInButton;
	@BindView(id = R.id.work_visit_button_upload, click = true)
	private Button mUploadButton;

	@BindView(id = R.id.work_recorder_main)
	private RelativeLayout mRecorderLayout;
	@BindView(id = R.id.work_name)
	private TextView mRecorderName;
	@BindView(id = R.id.work_stop, click = true)
	private Button mPauseButton;

	private LocationBroadcastReceiver mLocationBroadcastReceiver;
	private LocationBean mLocationBean;

	private LocationClient mLocationClient;
	private AppContext mAppContext;
	private Context mContext;
	private WorkVisitAdapter mWorkVisitAdapter;
	private KJDB mKjdb;
	private List<WorkVisitBean> mWorkVisitBeans;
	private int mMaxId;
	private WorkVisitBean mWorkVisitBean;

	private MatchFingerprintSyncLogic mLogic;
	private List<String> mCacheCheckImages = new ArrayList<String>();
	private int mChooseImageCount = 5;

	private RecordBean mRecordBean;
	private LoadingDialog mProgressDialog;

	private boolean mIsChoosePhoto = false; //判断是否用户进行了图片拍摄

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.kymjs.aframe.ui.activity.I_KJActivity#setRootView()
	 */
	@Override
	public void setRootView() {
		setContentView(R.layout.activity_work_visit);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.kymjs.aframe.ui.activity.KJFrameActivity#initWidget()
	 */
	@Override
	protected void initWidget() {
		// TODO Auto-generated method stub
		super.initWidget();
	}


	@Override
	protected void onEventCallBack(String event) {
		super.onEventCallBack(event);
		if ("recorder_finished".equals(event)){
			//隐藏录音模块
			mRecorderLayout.setVisibility(View.GONE);
		}else if ("recorder_start".equals(event)){
			updateRecorderState();
		}
	}

	public void onEventPostThread(String action){

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.kymjs.aframe.ui.activity.KJFrameActivity#initData()
	 */
	@Override
	protected void initData() {
		super.initData();
		mAppContext = (AppContext) getApplication();
		mContext = getApplicationContext();
		mKjdb = mAppContext.getKjdb();
		mTitleTextView.setText("工作走访");
		mWorkVisitAdapter = new WorkVisitAdapter(mContext);
		try {
			mWorkVisitBeans = mKjdb.findAll(WorkVisitBean.class);
		} catch (Exception e) {
		}
		mWorkVisitAdapter.addAll(mWorkVisitBeans);
		mListView.setAdapter(mWorkVisitAdapter);
		mListView.setOnItemClickListener(this);
		mProgressDialog = new LoadingDialog(this);
		initFinger();
	}

	// 初始化指纹信息
	private void initFinger() {
		MtRfid.getInstance().RfidInit();
		MtRfid.getInstance().SetContext(this);

//		mLogic = MatchFingerprintSyncLogic.getInstance();
		mLogic = new MatchFingerprintSyncLogic();
//		mLogic.setFingerPrintReader(SerialPortManager.getInstance()
//				.getNewAsyncFingerprint());
		mLogic.setHandle(mWorkVisitFingerpringHandler);
		mLogic.isManager(true);
	}

	private void showPopWindow() {
		mProgressDialog.setMessage("请按指纹...");
		mProgressDialog.show();
		fingerPrintMatch();
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.i(TAG, "<onResume> start service");
//		if (startService(new Intent(this, SoundRecorderService.class)) == null) {
//			Log.e(TAG, "<onResume> fail to start service");
//			finish();
//			return;
//		}
		updateRecorderState();
		//录音
		if (mIsChoosePhoto){
			//进行录音的选择
			mIsChoosePhoto = false;
			recording();
		}
	}


	private void updateRecorderState(){
		int state = HomeActivity.mHomeActivity.mService.getRecordState();

		boolean ongoing = state == SoundRecorder.STATE_RECORDING
				|| state == SoundRecorder.STATE_PLAYING;
		if (ongoing) {
			//显示，初始化数据
			mRecorderLayout.setVisibility(View.VISIBLE);
			SoundBean soundBean = HomeActivity.mHomeActivity.mService.getSoundBean();
			if (soundBean != null && soundBean.getServiceId() == UploadToTempSyncLogic.SERVICE.SERVICE_WORK_VISIT){
				WorkVisitBean bean = (WorkVisitBean) soundBean.source;
				if (bean != null){
					String fileName = TextUtils.isEmpty(HomeActivity.mHomeActivity.mService.getFileName()) ? "" :  " : " + HomeActivity.mHomeActivity.mService.getFileName();
					mRecorderName.setText(bean.getRymcName() + fileName);
				}
			}
		} else{
			//隐藏
			mRecorderLayout.setVisibility(View.GONE);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	// 开启指纹登录
	private synchronized void fingerPrintMatch() {
		if (DEBUG) {
			// 调试--模拟工作人员指纹
			List<FingerPrintBean> list = mKjdb.findAllByWhere(
					FingerPrintBean.class, "type =2");
			if (list == null || list.isEmpty()) {
				mFingerPrintBean = new FingerPrintBean();
				mFingerPrintBean.setUserName("gpnc");
				mFingerPrintBean.setUserId("100006");
				mFingerPrintBean.setType(2);
			} else {
				Random radom = new Random();
				int i = radom.nextInt(list.size());
				mFingerPrintBean = list.get(i);
			}
			// 选择矫正人员
			if (mFingerPrintBean != null && mFingerPrintBean.getType() == 2) {
				chooseRecordInfo(CHOOSE_RECORD_REQUEST_OK);
			}else {
				Toast.makeText(mContext, "匹配失败", Toast.LENGTH_SHORT).show();
			}
		} else {
			mLogic.execute();
		}
	}

	private Handler mWorkVisitFingerpringHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Message message = new Message();
			switch (msg.what) {
				case UIHelper.FINGERPRINT_UPCHAR_SUCCESS:
					break;
				case UIHelper.FINGERPRINT_UPCHAR_FAIL:// char--返回失败
				case UIHelper.FINGERPRINT_REGMODE_FAIL:// char--模板合成失败
				case UIHelper.FINGERPRINT_GENCHAR_FAIL:// char--生成特征值失败
				case UIHelper.FINGERPRINT_DELETECHAR_FAIL:// char--模板下载失败
				case UIHelper.FINGERPRINT_UPIMAGE_FAIL:// image--生成失败
				case UIHelper.FINGERPRINT_SEARCH_FAIL:
					message.what = 101;
					mMatchHandler.handleMessage(message);
					break;
				case UIHelper.FINGERPRINT_SEARCH_SUCCESS:
					// 匹配成功
//				Toast.makeText(mContext, "匹配成功", Toast.LENGTH_SHORT).show();
					int pageId = msg.arg1;
					message.what = 100;
					message.arg1 = pageId;
					mMatchHandler.handleMessage(message);
					break;
				case UIHelper.FINGERPRINT_AGAIN:// 再次按手指
					mProgressDialog.setMessage("请再次按指纹...");
					mProgressDialog.show();
				case UIHelper.FINGERPRINT_ONMATCH_SUCCESS:// image--图片合成成功

					break;

				default:
					break;
			}
		};

	};

	// 指纹验证结果回调
	private Handler mMatchHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (mProgressDialog != null) {
				mProgressDialog.dismiss();
			}
			if (mProgressDialog != null) {
				mProgressDialog.dismiss();
			}
			switch (msg.what) {
				case 100:
					// 匹配成功
					int pageId = msg.arg1;
					getUserInfoById(pageId);
					break;
				case 101:
					// 匹配失败
//					Toast.makeText(mContext, "没有找到匹配的指纹", Toast.LENGTH_SHORT)
//							.show();
					takePhotoSign();
					break;

				default:
					break;
			}
		};
	};

	//进行拍照签到，选取矫正人员
	private void takePhotoSign() {
		// 拍照
		mRecordBean = null;
		new AlertDialog.Builder(this)
				.setTitle("拍照签到")
				.setMessage("没有找到匹配的指纹,是否进行拍照签到？")
				.setCancelable(true)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						chooseRecordInfo(CHOOSE_RECORD_PHOTO_REQUEST_OK);
					}

				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}

				}).create().show();
	}

	private FingerPrintBean mFingerPrintBean;

	// 根据指纹获取当前用户的id
	private void getUserInfoById(int pageId) {
		//
		Log.i(TAG,"getUserInfoById pageId:" + pageId);
		try {
			mFingerPrintBean = mKjdb.findById(pageId, FingerPrintBean.class);
			// 选择矫正人员
			if (mFingerPrintBean != null && mFingerPrintBean.getType() == 2) {
				chooseRecordInfo(CHOOSE_RECORD_REQUEST_OK);
			}else {
				Toast.makeText(mContext, "匹配失败", Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
			Toast.makeText(mContext, "匹配失败", Toast.LENGTH_SHORT).show();
		}
	}

	// 选取矫正人员
	private void chooseRecordInfo(int requestId) {
		Intent intent = new Intent(WorkVisitActivity.this, RecordActivity.class);
		intent.putExtra(RecordActivity.RECORD_STATE,
				RecordActivity.CHOOSE_RECORD_STATE);
		startActivityForResult(intent, requestId);
	}

	private void takePhoto(final int requestId) {
		// 拍照
		new AlertDialog.Builder(this)
				.setTitle("拍照")
				.setMessage("是否进行拍照？")
				.setCancelable(true)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent takePicture = new Intent(
								WorkVisitActivity.this,
								ChoosePhotoActivity.class);
						takePicture.putExtra(
								ChoosePhotoActivity.CHOOSE_PHOTO_COUNT,
								mChooseImageCount);
						startActivityForResult(takePicture,requestId);
					}

				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}

				}).create().show();
	}

	// 开启录音
	private void recording() {
		// 拍照
		new AlertDialog.Builder(this).setTitle("录音").setMessage("是否进行录音？")
				.setCancelable(true)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						soundRecord();
					}

				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 提示录音
						dialog.dismiss();
					}

				}).create().show();
	}

	private SoundBean mSoundBean;

	private void soundRecord() {
		mSoundBean = new SoundBean();
		mSoundBean.serviceId = UploadToTempSyncLogic.SERVICE.SERVICE_WORK_VISIT;
		mSoundBean.source = mWorkVisitBean;
		mSoundBean.modelName = "工作走访";
		startRecorder();
//		Intent intent = new Intent(this,RecorderManagerActivity.class);
//		intent.setAction(RecorderManagerActivity.INTENT_RECORDER_WORK_VISIT);
//		intent.putExtra(RecorderManagerActivity.KEY_SOURCE,mSoundBean);
//		intent.putExtra(RecorderManagerActivity.KEY_RECORD_COUNT,1);

//		final int state = mService.getRecordState();
//		switch (state) {
//		case SoundRecorder.STATE_RECORDING:
//			Toast.makeText(this, "正在录音中...", Toast.LENGTH_SHORT).show();
//			return;
//		case SoundRecorder.STATE_IDLE:
//			mRemainingTimeCalculator.reset();
//			mService.stopAudioPlayback();
//			mService.setNotificationClass(this.getClass());
//
//			if ((mAudioManager.getMode() == AudioManager.MODE_IN_CALL)
//					&& (mAudioSourceType == MediaRecorder.AudioSource.MIC)) {
//				mAudioSourceType = MediaRecorder.AudioSource.VOICE_UPLINK;
//				mService.setAudioSourceType(mAudioSourceType);
//				Log.e(TAG, "Selected Voice Tx only Source: sourcetype"
//						+ mAudioSourceType);
//			}
//
//			mService.record(mRequestedType);
//			return;
//		}
	}

	private void startRecorder(){
		int state = HomeActivity.mHomeActivity.mService.getRecordState();

		boolean ongoing = state == SoundRecorder.STATE_RECORDING
				|| state == SoundRecorder.STATE_PLAYING;
		if (ongoing){
			new AlertDialog.Builder(WorkVisitActivity.this).setTitle("录音提示")
					.setMessage("录音正在使用，是否继续录音？").setCancelable(true)
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							//TODO 保存
							save();
							//TODO 开始
							new Handler().postDelayed(new Runnable() {
								@Override
								public void run() {
									start();
								}
							},500l);
							dialog.dismiss();
						}

					}).setNegativeButton("取消", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {

					dialog.dismiss();
				}

			}).create().show();
		}else{
			//TODO 开始
			start();
		}

	}

	private void save(){
		Intent intent = new Intent(HomeActivity.INTENT_RECORD_STOP);
		intent.putExtra(HomeActivity.KEY_RECORD_SOUND,mSoundBean);
		sendBroadcast(intent);
	}

	private void start(){

		Intent intent = new Intent(HomeActivity.INTENT_RECORD_START);
		intent.putExtra(HomeActivity.KEY_RECORD_SOUND,mSoundBean);
		sendBroadcast(intent);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.kymjs.aframe.ui.activity.KJFrameActivity#registerBroadcast()
	 */
	@Override
	public void registerBroadcast() {
		// TODO Auto-generated method stub
		super.registerBroadcast();
		initLocationBroadcast();
	}

	// 初始化获取当前位置的广播
	private void initLocationBroadcast() {
		mLocationClient = ((AppContext) getApplication()).mLocationClient;
		mLocationClient.start();
		mLocationBroadcastReceiver = new LocationBroadcastReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(MyLocationListener.LOCATION_INTENT);
		registerReceiver(mLocationBroadcastReceiver, filter);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.kymjs.aframe.ui.activity.KJFrameActivity#unRegisterBroadcast()
	 */
	@Override
	public void unRegisterBroadcast() {
		// TODO Auto-generated method stub
		super.unRegisterBroadcast();
		if (mLocationBroadcastReceiver != null) {
			unregisterReceiver(mLocationBroadcastReceiver);
		}
		if (mLocationClient != null) {
			mLocationClient.stop();
		}
	}

	// 获取当前的位置
	private class LocationBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {

			if (intent != null
					&& intent.getAction().equals(
					MyLocationListener.LOCATION_INTENT)) {

				mLocationBean = (LocationBean) intent
						.getSerializableExtra(MyLocationListener.LOCATION_KEY);
				Log.i(TAG, "-----> LocationBroadcastReceiver " + mLocationBean);
			}

		}
	};

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.kymjs.aframe.ui.activity.KJFrameActivity#widgetClick(android.view
	 * .View)
	 */
	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		switch (v.getId()) {
			case R.id.header_back:
				KJActivityManager.create().finishActivity(this);
				break;
			case R.id.work_visit_button_sign_in:
				// 签到拍照
				if (AppContext.FLAG_ONLY_ACCOUNT){
					UserBean bean = AppContext.getInstance().getUserBean();
					mFingerPrintBean = new FingerPrintBean();
					if (bean != null){
						mFingerPrintBean.setUserName(bean.getUserName());
						mFingerPrintBean.setUserId(String.valueOf(bean.getUserId()));
						mFingerPrintBean.setType(2);
					}
					chooseRecordInfo(CHOOSE_RECORD_REQUEST_OK);
				}else {
					SignIn();
				}
				break;
			case R.id.work_visit_button_upload:
				// 记录上传
				mProgressDialog.setMessage("请稍等，正在上传记录...");
				mProgressDialog.show();
				InsertVisitSyncLogic logic = new InsertVisitSyncLogic(mAppContext,
						mInsertVisitHandler, true);
				logic.execute();
				break;
			case R.id.work_stop:
				//停止录音
				int state = HomeActivity.mHomeActivity.mService.getRecordState();

				boolean ongoing = state == SoundRecorder.STATE_RECORDING
						|| state == SoundRecorder.STATE_PLAYING;
				mRecorderLayout.setVisibility(View.GONE);
				if (ongoing){
					save();
				}
				//隐藏录音
				break;
			default:
				break;
		}
	}

	// 签到拍照
	private void SignIn() {
		// 1.工作人员指纹签到
		showPopWindow();
		// 2.选择矫正人员
		// 3.提示拍照
		// 4.提示录音
	}

	private Handler mInsertVisitHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (mWorkVisitAdapter != null){
				try {
					mWorkVisitBeans = mKjdb.findAll(WorkVisitBean.class);
				} catch (Exception e) {
				}
				mWorkVisitAdapter.addAll(mWorkVisitBeans);
			}
			switch (msg.what) {
				case UIHelper.WORK_VISIT_UPLOAD_SUCCESS:
					// 上传图片
					UploadToTempSync();
					break;
				case UIHelper.WORK_VISIT_UPLOAD_FAIL:
					Log.i(TAG,"***************************************************");
					UploadToTempSync();
					break;

				default:
					break;
			}
		};
	};

	private void UploadToTempSync(){
		UploadToTempSyncLogic uploadToTempSyncLogic = new UploadToTempSyncLogic(
				mAppContext, mUploadToTempHandler, true, UploadToTempSyncLogic.SERVICE.SERVICE_WORK_VISIT);
		uploadToTempSyncLogic.execute();
	}

	private Handler mUploadToTempHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (mProgressDialog != null) {
				mProgressDialog.dismiss();
			}
			switch (msg.what) {
				case UIHelper.FILE_UPLOAD_SUCCESS:
					Toast.makeText(mContext, "记录上传成功", Toast.LENGTH_SHORT).show();
					break;
				case UIHelper.FILE_UPLOAD_FAIL:
					Toast.makeText(mContext, "记录上传失败", Toast.LENGTH_SHORT).show();
					break;

				default:
					break;
			}
		};
	};

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
							long id) {
		WorkVisitBean bean = (WorkVisitBean) parent.getItemAtPosition(position);
		if (bean != null) {
			Intent intent = new Intent(WorkVisitActivity.this,
					WorkVisitDetailActivity.class);
			intent.putExtra("WorkVisitBean", bean);
			startActivity(intent);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Log.i(TAG, "---> onActivityResult requestCode:" + requestCode + "resultCode:" + resultCode);
		if (requestCode == DialogHelper.CHOOSE_PHOTO_REQUEST_OK && resultCode == 1001) {
			// beginDailyReport();
			if (data != null) {
				mCacheCheckImages = data
						.getStringArrayListExtra("mCacheCheckImages");
				// 保存图片到数据库
				if (mCacheCheckImages != null && !mCacheCheckImages.isEmpty()) {
					Message message = new Message();
					message.what = 100;
					mSavePhotoHandler.sendMessage(message);
				}
			}
		}
		if (requestCode == CHOOSE_RECORD_REQUEST_OK && resultCode == RESULT_OK) {
			if (data != null) {
				mRecordBean = (RecordBean) data
						.getSerializableExtra("RecordBean");
				if (mRecordBean != null
						&& !StringUtils.isEmpty(mRecordBean.getElectronicsId())) {
					// 1.保存信息
					saveWorkVisitInfo();
				} else {
					Toast.makeText(mContext, "选择失败，请重新选择矫正人员信息",
							Toast.LENGTH_SHORT).show();
				}
			}
		}

		if (requestCode == CHOOSE_RECORD_PHOTO_REQUEST_OK && resultCode == RESULT_OK) {
			if (data != null) {
				mRecordBean = (RecordBean) data
						.getSerializableExtra("RecordBean");
				if (mRecordBean != null
						&& !StringUtils.isEmpty(mRecordBean.getElectronicsId())) {
					//TODO 打开拍照信息
					takePhoto(DialogHelper.CHOOSE_PHOTO_RECORD_REQUEST_OK);
				} else {
					Toast.makeText(mContext, "选择失败，请重新选择矫正人员信息",
							Toast.LENGTH_SHORT).show();
				}
			}
		}
		if (requestCode == DialogHelper.CHOOSE_PHOTO_RECORD_REQUEST_OK && resultCode == 1001) {
			if (data != null) {
				mCacheCheckImages = data
						.getStringArrayListExtra("mCacheCheckImages");
				if (mRecordBean != null){
					// 保存图片到数据库
					if (mCacheCheckImages != null && !mCacheCheckImages.isEmpty()) {
						Message message = new Message();
						message.what = 101;
						mSavePhotoHandler.sendMessage(message);
					}
				}
			}
		}
	}

	private void saveWorkVisitInfo() {
		if (mRecordBean != null && mFingerPrintBean != null
				&& mLocationBean != null) {
			WorkVisitBean bean = new WorkVisitBean();
			bean.setUserId(mFingerPrintBean.getUserId());
			bean.setUserName(mFingerPrintBean.getUserName());
			bean.setRymcId(mRecordBean.getElectronicsId());
			bean.setRymcName(mRecordBean.getName());
			bean.setMachId(mRecordBean.getRegisteredId());
			bean.setMachName(mRecordBean.getRegistered());
			bean.setInterViewTime(System.currentTimeMillis());
			bean.setInterViewWqk("遵守规定");
			bean.setInterViewAddress(mLocationBean.getAddress());
			bean.setLatitude(mLocationBean.getLatitude());
			bean.setLongitude(mLocationBean.getLontitude());
			bean.setState(1);
			bean.setRegistrationType(0);
			mKjdb.saveBackId(bean);			// 获取当前保存的id
			DbModel dbModel = mKjdb
					.findDbModelBySQL("select max(id) as id from table_workVisit order by id desc");
			mMaxId = dbModel.getInt("id");
			bean.setId(mMaxId);
			mWorkVisitBean = bean;
			mWorkVisitAdapter.addOne(bean);
			Log.i(TAG, "----> saveWorkVisitInfo mMaxId:" + mMaxId);
			// 提示拍照
			takePhoto(DialogHelper.CHOOSE_PHOTO_REQUEST_OK);
		}else {
			Toast.makeText(mContext, "选择失败", Toast.LENGTH_SHORT).show();
		}
	}


	private boolean saveWorkVisitInfoForPhoto() {
		if (mRecordBean != null && mLocationBean != null) {
			//TODO 获取当前登录着
			UserBean userBean = AppContext.getInstance().getUserBean();
			if (userBean == null){
				return false;
			}
			WorkVisitBean bean = new WorkVisitBean();
			bean.setUserId(String.valueOf(userBean.getUserId()));
			bean.setUserName(userBean.getUserName());
			bean.setRymcId(mRecordBean.getElectronicsId());
			bean.setRymcName(mRecordBean.getName());
			bean.setMachId(mRecordBean.getRegisteredId());
			bean.setMachName(mRecordBean.getRegistered());
			bean.setInterViewTime(System.currentTimeMillis());
			bean.setInterViewWqk("遵守规定");
			bean.setInterViewAddress(mLocationBean.getAddress());
			bean.setLatitude(mLocationBean.getLatitude());
			bean.setLongitude(mLocationBean.getLontitude());
			bean.setState(1);
			bean.setRegistrationType(1);
			mKjdb.saveBackId(bean);			// 获取当前保存的id
			DbModel dbModel = mKjdb
					.findDbModelBySQL("select max(id) as id from table_workVisit order by id desc");
			mMaxId = dbModel.getInt("id");
			bean.setId(mMaxId);
			mWorkVisitBean = bean;
			mWorkVisitAdapter.addOne(bean);
			Log.i(TAG, "----> saveWorkVisitInfo mMaxId:" + mMaxId);
			return true;
		}
		Toast.makeText(mContext, "保存失败", Toast.LENGTH_SHORT).show();
		return false;
	}

	private Handler mSavePhotoHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case 100:
					savePhoto();
					//TODO 开启录音
					recording();
					break;
				case 101:
					//TODO 拍照签到 保存数据
					if (saveWorkVisitInfoForPhoto()){
						//保存图片
						savePhoto();
						//TODO 开启录音
						recording();
					}
					break;

				default:
					break;
			}
		};
	};

	// 把选取的图片保存到数据库
	private void savePhoto() {
		if (mCacheCheckImages != null && !mCacheCheckImages.isEmpty()) {
			int size = mCacheCheckImages.size();
			for (int i = 0; i < size; i++) {
				String photoPath = mCacheCheckImages.get(i);
				Log.i(TAG, "---> savePhoto:" + photoPath);
				ImageOrAudioBean bean = DataHelper
						.getImageOrAudioBeanInfoByPath(this, photoPath, 1);
				bean.setServiceId(4);
				bean.setParentId(String.valueOf(mMaxId));
				Log.i(TAG, "---> savePhoto " + bean);
				mKjdb.save(bean);
			}
		} else {
			Toast.makeText(this, "选取图片失败", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (mLogic != null) {
			mLogic.destory();
		}
		MtRfid.getInstance().RfidClose(); // Close
		//FingerprintManager.getInstance().closeSerialPort();
	}

}
